using System;
using System.Linq;
using System.Xml.Linq;
using TimerUppercut.Domain;

namespace TimerUppercut.Utils
{
    public static class XMLHelper
    {
        /// <summary>
        /// Generates the import XML.
        /// </summary>
        /// <param name="restore">The <see cref="Restore"/> file.</param>
        public static void GenerateXML(Restore restore)
        {
            var root = new XElement("TimerUppercut");
            root.Add(new XElement("Name", restore.Name));
            root.Add(new XElement("Date", restore.Date));

            foreach (var timer in restore.Timers)
            {
                root.Add(new XElement("Timer",
                                      new XElement("Id", timer.Id),
                                      new XElement("Description", timer.Description),
                                      new XElement("Hours", timer.Hours),
                                      new XElement("Minutes", timer.Minutes),
                                      new XElement("Seconds", timer.Seconds)));
            }

            var doc = new XDocument
                (
                new XDeclaration("1.0", "utf-8", "yes"),
                new XComment("Timer Uppercut generated import/export file"),
                root
                );

            doc.Save(restore.Name);
        }

        /// <summary>
        /// Loads the XML.
        /// </summary>
        /// <param name="filename">The filename.</param>
        /// <returns></returns>
        public static Restore LoadXML(string filename)
        {
            

            var doc = XDocument.Load(filename);


            var restore = (doc.Elements("TimerUppercut").
                Select(x => new Restore
                                {
                                    Name = x.Elements("Name").Single().Value,
                                    Date = Convert.ToDateTime(x.Elements("Date").Single().Value)
                                })).Single();

            restore.Timers = (doc.Elements("TimerUppercut").Elements("Timer").
                Select(x => new Timer
                                {
                                    Id = new Guid(x.Elements("Id").Single().Value),
                                    Description = x.Elements("Description").Single().Value,
                                    Hours = Convert.ToUInt64(x.Elements("Hours").Single().Value),
                                    Minutes = int.Parse(x.Elements("Minutes").Single().Value),
                                    Seconds = int.Parse(x.Elements("Seconds").Single().Value)
                                }
                ));


            return restore;
        }
    }
}